﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.EntityClient;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using MeresModeling;
using Orchard.Themes;

namespace Meres.Controllers
{
    [Themed]
    public class HtmlTreeController : Controller
    {
        public JsonResult GetFullGroupTree()
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var data = GetTreeItems(MeresMainController.Model);
                return Json(data, JsonRequestBehavior.AllowGet);
            }

        }

        private static TreeItem Convert(MembershipGroup m)
        {
            return new TreeItem
                       {
                           Id = m.Id,
                           ParentId = m.Parent == null ? null : (int?)m.Parent.Id,
                           data = m.Name,
                           Parent = null,
                           children = new List<TreeItem>(),
                           state = "open"
                       };
        }

        public JsonResult GroupOperation(string operation, string id)
        {
            return GetFullGroupTree();
        }
        public List<TreeItem> GetTreeItems(MeresModel db)
        {
            var data = db.MembershipGroups.ToList().Select(Convert).ToList();
            var dic = data.ToDictionary(t => t.Id, t => t);
            // Build hierachy
            data.ForEach(g =>
                             {
                                 if (g.ParentId == null)
                                     return;
                                 g.Parent = dic[(int)g.ParentId];
                                 g.Parent.children.Add(g);
                             });

            return data.Where(d => d.ParentId == null).ToList();
        }

        [HttpGet]
        public JsonResult GetGroupTreeChildren(int? id)
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var data = MeresMainController.Model.MembershipGroups.Single(g => g.Id == id).Children.ToList().Select(Convert);
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
    }

    public class TreeItem
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string data { get; set; }
        public object Tag { get; set; }
        [ScriptIgnore]
        public TreeItem Parent { get; set; }
        public List<TreeItem> children { get; set; }
        public string state { get; set; }
        public override string ToString()
        {
            return Id + ":" + data;
        }
    }
}
